package org.je.refl;

import java.util.HashMap;
import java.util.Map;

/**
 * 类PrimitiveClassUtil.java的实现描述： 类实现描述
 * 
 * @author fanyifeng 2012-8-30 下午3:41:18
 */
public class PrimaryClassUtil
{
	private static Map<Class<?>, Class<?>>	map	= new HashMap<Class<?>, Class<?>>();

	static {
		map.put(Boolean.class, boolean.class);
		map.put(Byte.class, byte.class);
		map.put(Character.class, char.class);
		map.put(Short.class, short.class);
		map.put(Integer.class, int.class);
		map.put(Long.class, long.class);
		map.put(Float.class, float.class);
		map.put(Double.class, double.class);
	}

	public static Object createObject(Class<?> cl) {
		return createObject(cl, null);
	}

	public static Object createObject(Class<?> cl, String value) {
		Class<?> useCl = cl.isPrimitive() ? cl : map.get(cl);
		return useCl == null ? null : createPrimitiveObject(useCl, value);
	}

	private static Object createPrimitiveObject(Class<?> cl, String val) {
		if (val == null)
			return createPrimitiveObject(cl);
		try {
			if (cl == int.class)
				return Integer.parseInt(val);
			if (cl == boolean.class) {
				if (val.startsWith("t"))
					return true;
				return false;
			}
			if (cl == byte.class)
				return (byte) Integer.parseInt(val);
			if (cl == char.class)
				return (char) val.charAt(0);
			if (cl == short.class)
				return (short) Integer.parseInt(val);
			if (cl == long.class)
				return Long.parseLong(val);
			if (cl == double.class)
				return Double.parseDouble(val);
			if (cl == float.class)
				return Float.parseFloat(val);
		} catch (Exception ex) {
			throw new IllegalArgumentException("format-primary-error:" + ex.getMessage());
		}
		return null;
	}

	private static Object createPrimitiveObject(Class<?> cl) {
		if (cl == int.class)
			return 0;
		if (cl == boolean.class)
			return false;
		if (cl == byte.class)
			return (byte) 0;
		if (cl == char.class)
			return (char) 0;
		if (cl == short.class)
			return (short) 0;
		if (cl == long.class)
			return 0L;
		if (cl == double.class)
			return 0.0;
		if (cl == float.class)
			return 0.0F;
		return null;
	}

}
